import React, { FC, useState, useRef, useEffect } from "react";
//关于闭包陷阱
const Closuretrap: FC = () => {
  const [num, setnum] = useState(0);
  const addnum = () => {
    setnum(num + 1);
  };
  const refCount = useRef(0);
  useEffect(() => {
    refCount.current = num;
  }, [num]);

  const showinfo = () => {
    setTimeout(() => {
      alert(refCount.current);
    }, 1500);
  };
  return (
    <>
      <p>闭包陷阱</p>
      <button onClick={addnum}> 增加数子--{num} </button>
      <button onClick={showinfo}>异步显示alert数字</button>
    </>
  );
};

export default Closuretrap;
